$(function() {

	var t_brandNameCh = $("#brandNameCh").val();
	var t_brandImage = $("#brandImage").val();
	
	$("#productBrandForm").validate({
		rules : {
			brandNameCh : {
				required : true
			},
			brandImage : {
				required : true
			}
		},
		messages : {
			brandNameCh : {
				required : '请填写中文名称'
			},
			brandImage : {
				required : '请上传品牌LOGO'
			}
		},
		errorPlacement : function(error, element) { // 错误信息位置设置方法
			var tagName = $(element).is("select");
    		if(!tagName) {
    			error.insertAfter(element);
    		}else {
    			error.insertAfter(element.parent().next());
    		}
		},
		submitHandler : function(form) {
			$(form).ajaxSubmit({
		       	type		: 'post',
		       	//url		: url, 
		       	clearForm	: false,  
				resetForm	: false,  
				timeout		: 5000, 
		       	success		: function(json){
	       	        //返回结果 {"code":23,"msg":"新增商品品牌成功"}
                    var index = parent.layer.getFrameIndex(window.name);
                    if(json.code == '0') {
                        parent.$('#opt_status').val('0'); 
                        showErr(json.msg); 
                    } else {
                        parent.$('#opt_status').val('1'); 
                        parent.layer.close(index);
                    }
//		       		var index = parent.layer.getFrameIndex(window.name);
//		           	if (json.code == '1') {
//		           		parent.layer.close(index);
//		           	} else { 
//		           		showErr('新增失败！');
//		        	}
		     	}
			}); 
		}
	});
	
	//提交
	$("#btn_save").click(function() {
		$("#productBrandForm").submit();
		return false;
	});
	
	//关闭
	$("#btn_back").click(function() {
		var index = parent.layer.getFrameIndex(window.name);
   		parent.layer.close(index);
	});
	
	//品牌名称失去焦点时自动转化成首字母并赋值到品牌首字母中
	$("#brandNameCh").blur(function() {
		var brandNameChValue = $("#brandNameCh").val();
		//获取首字母
		var fristLatter = makePy(brandNameChValue);
		//赋值
		$("#brandLetterFrist").val(fristLatter);
	});
	
	//初始化上级品牌树
	brandTreeMenu.init();
	//选择上级品牌
 	$(".dropDownTreeMenu").on("click", function(){   
 		brandTreeMenu.showTreeMenu();
	});
});


//通过ajax提交图片
function ajaxFileUpload(obj) {
	var lis = $("#image_container").find("li");
	if (lis.length > 1) {
		msg("只能上传一张照片");
		return false;
	}
	var id = $(obj).attr("id");
	var check = imageCheck(obj);
	if (!check) {
		return;
	}
	$.ajaxFileUpload({
				url : rootPath + '/uploadFile/uploadOneFile',
				secureuri : false,
				fileElementId : id, // input标签id属性值
				dataType : 'json',
				success : function(data, status) {
					if (data.code == 1) {
						var oldLi = "<li>"
							+"<div class=\"pic1\">"
							+"<img src=\""
							+rootPath
							+"/statics/images/upload_pic1.png\" />"
							+"<input id=\"upload_brand_image\" type=\"file\" name=\"upload_brand_image\" onchange=\"ajaxFileUpload(this)\" />"
							+"</div>" + "</li>";
						
						var li = "<li>"
								+ "	<div class=\"pic1\">"
								+ "		<img src=\""
								+ imgRootURL
								+ data.filePath
								+ "\" />"
								+ "		<a id=\"btn_close\" href=\"javascript:void(0)\" class=\"icon_close\"></a>"
								+ "      <input type=\"hidden\" name=\"brandImage\" value=\""
								+ data.filePath + "\" />" + "	</div>" + "</li>";
						$("#image_container").empty();
						$("#image_container").append(li);
						$("#image_container").find("a").each(function() {
							$(this).click(function() {
								$(this).closest("li").remove();
								$("#image_container").append(oldLi);
							});
						});

					} else {
						msg("上传失败");
					}
				},
				error : function(data, status, e) {
					msg("系统异常");
				}
		});
}

//检查图片格式及大小
function imageCheck(obj){
	var id = $(obj).attr("id");
	var filePath = $("#"+id).val();
	//检查后缀
	var ext = filePath.substring(filePath.lastIndexOf("."), filePath.length).toUpperCase();
	if (ext != ".BMP" && ext != ".PNG" && ext != ".GIF" && ext != ".JPG" && ext != ".JPEG") {
		layer.msg('只能上传图片',{time:500});
		return false;
	}
	var file_size = 0;
	if (false || !!document.documentMode) {
		var img = new Image();
		img.src = filepath;
		while (true) {
			if (img.fileSize > 0) {
				if (img.fileSize > 5 * 1024 * 1024) {
					layer.msg('图片不能大于5MB',{time:1000});
					return false;
				}
				break;
			}
		}
	} else {
		file_size = obj.files[0].size;
		var size = file_size / 1024;
		if (size > 5120) {
			layer.msg('图片不能大于5MB',{time:1000});
			return false;
		}
	}
	return true;
}

/**
 * 组织菜单树模块
 */
var brandTreeMenu = (function(){
	var treeName = "treeMenu";
	var tree = $("#" + treeName);
	var brandContent = $("#brandContent");
	var pBrandNameObj = $("#parentBrandName");
	var pIdObj = $("#parentBrandCode");
	
	var URLs = {
			listBrand : rootPath + "/productBrand/getProductBrandMap"
		};
	var setting = {
			data : {
				simpleData : {
					enable  : true,
					idKey   : 'id',
					pIdKey  : 'parentBrandCode',
					rootPId : "0"
				}
			},
			callback : {
				onClick	: onClick
			}
	};
	
	/**
	 * 隐藏树按钮
	 */
	var hideTreeMenu = function(){
		brandContent.fadeOut("fast");
		$("body").unbind("mousedown", onBodyDown);
	}
	
	/**
	 * 显示藏树按钮
	 */
	 var showTreeMenu = function(){
	 	var obj = pBrandNameObj;
		var offset = pBrandNameObj.offset();
	 	if (brandContent.is(":hidden")){
	 		brandContent.css({left:offset.left + "px", top:offset.top 
				+ obj.outerHeight() + "px", width: obj.width() + "px"}).slideDown("fast");
			$("body").bind("mousedown", onBodyDown);
	 	}else{ 
	 		hideTreeMenu();
	 	}
	 }

	/**
	 *body区域鼠标点击事件
	 */
	var onBodyDown = function(event) {
		if (!( event.target.id == "brandContent" || $(event.target).parents("#brandContent").length > 0)) {
			hideTreeMenu();
		}
	}
	
	/**
	 *点击菜单树事件
	 */
	function onClick(e, treeId, treeNode) {  
		var zTree = $.fn.zTree.getZTreeObj(treeName), 
			nodes = zTree.getSelectedNodes(), 
			name = "", 
			id = "";
		nodes.sort(function compare(a, b) {
			return a.id - b.id;
		});
		for ( var i = 0, l = nodes.length; i < l; i++) {
			name += nodes[i].name + ",";
			id += nodes[i].id + ","; 
		}
		if (id.length > 0)
			id = id.substring(0, id.length - 1);
		if (name.length > 0)
			name = name.substring(0, name.length - 1); 
			
		pBrandNameObj.val(name);
		pIdObj.val(id); 
		hideTreeMenu();
		
	};
	
	return { 
		showTreeMenu: showTreeMenu,
		/**
		 * 创建组织树
		 * @returns 返回初始化后的zTree对象
		 */
		init: function(){
			var nodes = [];
			/**
			 * 查询所有品牌
			 */
			$.ajax({
				url : URLs.listBrand,
				async : false,
				dataType : 'json',
				type : 'post',
				success : function(result) {
					if (result.data != null) {
						$.each(result.data, function(index, row) {
							nodes.push({
								id : row.id,
								parentId : row.parentBrandCode,
								name : row.brandNameCh
							});
						});
					}
				}
			});
			var treeObj = $.fn.zTree.init(tree, setting, nodes);
			//全部展开
			treeObj.expandAll(true); 
			return treeObj;
		}
	}
})();
